package com.sky.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebSocketServer {

    private static Map<String, Session> sessionMap=new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        log.info("客户端："+sid+"建立连接");
        sessionMap.put(sid,session);
    }

    @OnMessage
    public void onMessage(String message,@PathParam("sid") String sid){
        log.info("收到来自客户端："+sid+"的信息："+message);
    }
    @OnClose
    public void onClose(@PathParam("sid") String sid){
        log.info("客户端："+sid+"断开连接");
        sessionMap.remove(sid);
    }

    /**
     * 群发消息
     * @param message
     */
    public void sendToAllClient(String message){
        Collection<Session> values = sessionMap.values();
        for (Session session : values) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
